#!/usr/bin/env bash
#-------------------------------------------------------
#	FileName	: ice.sh
#	Author		：hpy
#	Date		：2022年08月06日
#	Description	：iCESugar-nano 工具链管理脚本
#-------------------------------------------------------
#cd $(dirname $0)
shell_name=$(basename $0)

# 引入 msys 安装的FPGA工具链路径，放在PATH最前面 
PATH=/cygdrive/d/msys64/mingw64/bin:$PATH
icesprog="icesprog"   #iceprog.exe的路径
yosys="yosys" 

if [[ "$1" == "-h" ]] || [[ "$1" == "--help" ]] || [[ "$1" == "-help" ]]  || [[ "$1" == "help" ]] ; then 
cat<<EOF
$(basename $0) -v 1.0 
iCESNano FPGA开发板工具
Usage: $(basename $0) [option] [filename]			
    $(basename $0) build [filename]         综合,filename为顶层文件名称
    $(basename $0) prog                     将当前路径下的bin文件下载到icesugar开发板中
    $(basename $0) filename                 综合filename文件并下载到硬件中去 
    $(basename $0) time                     时序分析
    $(basename $0) clean                    清除生成的文件
    $(basename $0) clk [1|2|3|4]            设置时钟频率 8MHz|12MHz|36MHz|72MHz
    $(basename $0) help/-h                  显示使用帮助
示例
	$(basename $0) build top.v 
EOF
exit 0
fi 

function main(){
    # test ! -f $1 && echo "不存在 $1 文件" | cat && exit

    case $1 in 
        build) build $2 ;;
        prog) prog ;;
        time) micetime ;;
        clean)clean_f ;;
        clk) setclkfreq $2;; 
        *.v) clean_f && build $1 && prog ;;  
        *) ;;
    esac 
}




function prog() {
    echo ""
    echo "INFO:start write bin to FPGA"
    ICELINK_DIR=$(df | grep iCELink | awk '{print $6}')
    echo "ICELINK_DIR=$ICELINK_DIR"
    filename=$(ls *.bin)
    test $? -ne 0 && echo "info:*.bin文件不存在" |cat && exit
    #使用icesprog 
    # sudo icesprog $filename  
    eval "$icesprog $filename" 

    exit 0
    # 使用虚拟磁盘的方式
    if [ -d $ICELINK_DIR ]; 
        then 
            cp $filename $ICELINK_DIR 
            echo "prog done!"
        else 
            echo "iCELink not found" 
            exit 1 
    fi
}


function setclkfreq() {
    test $1 -lt 1 && exit 
    test $1 -gt 4 && exit 
    eval "$icesprog -c $1" 
}

# 综合  , 输入为顶层文件
function build() {
    test ! -f $filename && echo "info:$filename文件不存在" |cat && exit
    filename=$(basename $1)
    filename=$(echo $filename|cut -d . -f1)
    
    pcf_file=$(ls *.pcf) 
    test $? -ne 0 && echo "info:IO约束文件 *.pcf 文件不存在" |cat && exit

    $yosys -p "synth_ice40 -json ${filename}.json -blif ${filename}.blif" ${filename}.v
	nextpnr-ice40 --lp1k --package cm36 --json ${filename}.json --pcf ${pcf_file} --asc ${filename}.asc --freq 48
	# arachne-pnr -d 1k -P cm36 -p ${pcf_file}  ${filename}.blif -o ${filename}.asc
	icepack ${filename}.asc ${filename}.bin

}

function clean_f() {
    rm -rf *.blif *.asc *.bin *.json *.log *.history
}

#时序分析
function micetime() {
    ls *.v
    test $? -ne 0 && echo "info:*.asc 文件不存在" |cat && exit
    icetime -tmd lp1k *.asc
}


main $*
